package com.zzyl.nursing.service.impl;

import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;

import com.zzyl.common.utils.DateTimeZoneConverter;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.IotDataVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.time.LocalDateTime;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;

/**
 * 设备Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private IoTDAClient client;

    /**
     * 查询设备
     *
     * @param id 设备主键
     * @return 设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备列表
     *
     * @param device 设备
     * @return 设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备
     *
     * @param device 设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备
     *
     * @param ids 需要删除的设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备信息
     *
     * @param id 设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        ListProductsRequest requst = new ListProductsRequest();
        requst.setLimit(50);
        ListProductsResponse response = client.listProducts(requst);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        List<ProductSummary> products = response.getProducts();
        //保存在redis缓存中
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从redis缓存中获取产品中id以及name
        String products = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);
        if (StrUtil.isEmpty(products)) {
            return new ArrayList<>();
        }
        return JSONUtil.toList(products, ProductVo.class);
    }

    @Override
    public void register(DeviceDto dto) {
        //判断设备名称是否存在
        long count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()));
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        //判断设备编号nodeid是否存在
        count = this.count(Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId()));
        if (count > 0) {
            throw new BaseException("设备编号已存在");
        }
        //同一位置是否绑定了相同的产品
        count = this.count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())//位置id
                .eq(Device::getProductKey, dto.getProductKey())//产品key
                .eq(Device::getLocationType, dto.getLocationType())//位置类型
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())//物理位置类型(有可能不存在)
        );
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //注册设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());//产品id
        body.setNodeId(dto.getNodeId());//节点id
        body.setDeviceName(dto.getDeviceName());//设备名称
        AuthInfo authinfo = new AuthInfo();
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authinfo.setSecret(secret);
        body.setAuthInfo(authinfo);//密钥
        request.setBody(body);
        AddDeviceResponse response = client.addDevice(request);
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("物联网接口 - 注册设备，同步失败");
        }
        //保存到数据库device表中
        Device device = BeanUtil.toBean(dto, Device.class);
        // 秘钥
        device.setSecret(secret);
        // 设备id、设备绑定状态
        device.setIotId(response.getDeviceId());
        this.save(device);
    }

    /**
     * 查询设备详情数据
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库中的数据
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            throw new BaseException("设备不存在");
        }
        //查询iot平台数据
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备详情，同步失败");
        }
        String status = response.getStatus();
        String activeTimeStr = response.getActiveTime();
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);
        // 日期转换
        if (StrUtil.isNotEmpty(activeTimeStr)) {
            // 日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            vo.setActiveTime(activeTime);
        }
        vo.setDeviceStatus(status);
        return vo;
    }

    /**
     * 查询设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<IotDataVo> queryServiceProperties(String iotId) {
        //通过iot平台查询上报数据
        ShowDeviceShadowRequest requset = new ShowDeviceShadowRequest();
        requset.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(requset);
        if (ObjectUtil.isEmpty(response)){
            return null;
        }
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询设备上报数据，同步失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (ObjectUtil.isEmpty( shadow)){
            return new ArrayList<>();
        }
        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        if (StrUtil.isEmpty(eventTimeStr)){
            throw new BaseException("物联网接口 - 获取设备上报数据时间失败");
        }
        // 把字符串转换为LocalDateTime
        LocalDateTime eventTimeLocalDateTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
        // 时区转换
        LocalDateTime eventTime = DateTimeZoneConverter.utcToShanghai(eventTimeLocalDateTime);
        Object properties = shadow.get(0).getReported().getProperties();
        JSONObject entries = JSONUtil.parseObj(properties);
        List<IotDataVo> list = new ArrayList<>();
        for (Map.Entry<String, Object> entry : entries) {
            IotDataVo vo = new IotDataVo();
            vo.setFunctionId(entry.getKey());
            vo.setEventTime(String.valueOf(eventTime));
            vo.setValue(entry.getValue().toString());
            list.add(vo);
        }
        //封装上报数据返回
        return list;
    }

    @Override
    public void edit(DeviceDto dto) {
        //先修改IoTDA平台上的设备名称
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        if (ObjectUtil.isEmpty(request)){
            throw new BaseException("物联网接口 - 修改设备名称，同步失败");
        }
        request.setDeviceId(dto.getIotId());
        UpdateDevice body = new UpdateDevice();
        body.setDeviceName(dto.getDeviceName());
        request.setBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        if (response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 修改设备名称，同步失败");
        }
        //再修改本地存储的设备信息
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setBindingLocation(String.valueOf(dto.getBindingLocation()));
        //注意：修改之后，不能在同一个位置绑定同一个产品
        long count = count(Wrappers.<Device>lambdaQuery()
                .eq(Device::getBindingLocation, dto.getBindingLocation())//位置
                .eq(Device::getProductKey, dto.getProductKey())// 产品
                .eq(Device::getLocationType, dto.getLocationType())//位置类型
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())//物理位置类型(有可能不存在)
        );
        if (count > 0){
            throw new BaseException("该位置已绑定该产品");
        }
        this.updateById(device);
    }
    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {
        //先从IoTDA平台删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);
        DeleteDeviceResponse response = client.deleteDevice(request);
        if(response.getHttpStatusCode()!= 204){
            throw new BaseException("物联网接口 - 删除设备，同步失败");
        }
        //再删除本地存储的设备
        boolean b = this.remove(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (!b){
            throw new BaseException("删除设备失败");
        }
    }

    @Override
    public List<ServiceCapability> queryProject(String productKey) {
        if (StrUtil.isEmpty(productKey)){
            throw new BaseException("产品ID不能为空");
        }
        ShowProductRequest request =new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct( request);
        if (ObjectUtil.isEmpty(response)) {
            return CollectionUtil.newArrayList();
        }
        if (response.getHttpStatusCode()!=200) {
            return CollectionUtil.newArrayList();
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (ObjectUtil.isEmpty(serviceCapabilities)){
            return CollectionUtil.newArrayList();
        }
        return serviceCapabilities;

    }

}
